package com.woniu.mall.task;

import com.woniu.common.entity.Result;
import com.woniu.mall.constant.OrderConstants;
import com.woniu.mall.constant.SeckillRedisKey;
import com.woniu.mall.feign.SeckillFeignClient;
import com.woniu.mall.pojo.MallSeckill;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class SeckillProductToRedisTask {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SeckillFeignClient seckillFeignClient;

    /**
     * 秒杀数据预热
     */
    @Scheduled(cron = "0 0 0 * * ?") // 每天凌晨0点执行一次
    public void seckillProductToRedis(){
        //1. 删除之前的秒杀数据
        redisTemplate.delete(SeckillRedisKey.SECKILL_LIST);
        //2. 调用商品服务查询正在进行的秒杀场次的商品
        List<MallSeckill> seckillList = seckillFeignClient.listStarting().getData();
        //3. 将秒杀的商品存储到redis中（Hash）
        if (seckillList != null && seckillList.size() > 0){
            for (MallSeckill seckill : seckillList) {
                redisTemplate.boundHashOps(SeckillRedisKey.SECKILL_LIST).put(seckill.getProductId() + "", seckill);
                //生成一个库存数量相同的令牌以防止超卖
                redisTemplate.boundListOps(SeckillRedisKey.SECKILL_ORDER_OVER + seckill.getProductId()).leftPushAll(pushId(seckill.getPsCount()));
            }

        }
    }

    /**
     * 根据商品数量生成一个对应长度的数组
     * @param len
     * @return
     */
    private Long[] pushId(int len){
        Long[] ids = new Long[len];
        for (int i = 0; i < ids.length; i++) {
            ids[i] = 1L;
        }
        return ids;
    }
}
